const message = require("../dao/messageDao");
const validate = require("validate.js");
const { ValidationError } = require("../utils/errors");
const { getAvatarPath } = require("../utils/tool");
// 添加留言
const addMessage = async (info) => {
  info.createDate = Date.now();
  info.avatar = await getAvatarPath();
  const rule = {
    nickname: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    content: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    createDate: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
    avatar: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
  };
  const validation = validate.validate(info, rule);
  if (!validation) {
    const result = await message.addMessage(info);
    return result;
  } else {
    console.log(validation);
    throw new ValidationError("数据验证失败");
  }
};

//删除留言
const deleteMessage = async (id) => {
  await message.deleteMessage(id);
  return true;
};

//分页获取留言
const getMessageList = async (page = 1, limit = 10, keyword = "") => {
  const info = { page, limit };
  const rule = {
    page: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
    limit: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
  };
  const validation = validate.validate(info, rule);
  if (!validation) {
    const result = await message.getMessageList(page, limit, keyword);
    return result;
  } else {
    throw new ValidationError("数据验证失败");
  }
};

module.exports = {
  addMessage,
  deleteMessage,
  getMessageList,
};
